#!/bin/bash

# copy_files_directory.sh
# This script copies all files from the source directory to the target directory if they are newer than the existing ones in the target directory, preserving the subdirectory structure.
# Usage: ./copy_files_directory.sh source_directory target_directory

# Validate arguments
if [ $# -ne 2 ]; then
    echo "Error: Incorrect number of arguments."
    echo "Usage: $0 source_directory target_directory"
    exit 1
fi

# Assign arguments to variables
source_directory=$1
target_directory=$2

# Ensure the source directory ends with a slash
source_directory="${source_directory%/}/"

# Function to copy a file to the specified directory if it is newer
copy_file() {
    local source_file="$1"
    local target_directory="$2"

    # Calculate the relative path from source_file
    local relative_path="${source_file#$source_directory}"
    local target_file="$target_directory/$relative_path"

    # Ensure target directory exists
    mkdir -p "$(dirname "$target_file")"

    # Check if the source file is newer than the target file and copy if so
    if [ "$source_file" -nt "$target_file" ]; then
        cp -u "$source_file" "$target_file"
        echo "\"$source_file\" has been updated on $(date +%Y-%m-%d-%H-%M-%S)!"
    fi
}

export -f copy_file

# Find all files in source directory and subdirectories, and process them
find "$source_directory" -type f | while IFS= read -r file; do
    copy_file "$file" "$target_directory"
done

